package jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//工具类
public class Utils1 {
    public static String url;
    public static String user;
    public static String password;
    public static String driver;

    //文件的读取只需要加再一次,所以放在静态代码,随着类的加载进来

    static {
        //创建集合对象
        try {
            Properties pp = new Properties();
            InputStream is = Utils1.class.getClassLoader().getResourceAsStream("jdbc.properties");
            pp.load(is);

            url = pp.getProperty("url");
            user = pp.getProperty("user");
            password = pp.getProperty("password");
            driver = pp.getProperty("driver");

            Class.forName(driver);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取数据
    public static Connection getconnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }

    //释放资源
    public static void close(Connection con, Statement sta, ResultSet res) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (sta != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (res != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
